const Model = require('./index')

class LoginLogModel extends Model {
  /**
   * 登录日志查询文章列表
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} conditions
   * @returns
   */
  async findPage ({ pageNo, pageSize, andConditions, orConditions, betweenConditions }) {
    const andSql = this.generateWhereClause(andConditions)
    const conditionSql = this.generateBetweenClause(betweenConditions, this.generateWhereClauseOR(orConditions, andSql))
    const sql = `select log.*, user.nickname, user.username, user.status from login_log log
      left join user on user.id = log.userId ${conditionSql} 
      order by log.loginTime desc
      limit ${pageSize} offset ${(pageNo - 1) * pageSize}`
    try {
      const list = await this.db.query(sql)
      const total = await this.total(conditionSql)
      return {
        list,
        total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  async total (conditionSql) {
    const sql = `select count(*) as total from login_log log 
    left join user on user.id = log.userId ${conditionSql}`
    try {
      const total = await this.db.query(sql)
      return total[0].total
    } catch (error) {
      throw new Error(error)
    }
  }

  async delete (ids) {
    const sql = 'delete from login_log where id in (?)'
    try {
      await this.db.query(sql, `${ids.join(',')}`)
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new LoginLogModel('login_log')
